<?php
class ManageMembersController extends AppController {

   var $uses = array('User','Licence','Club');

   var $components = array('RandomGenerator');

   var $helpers = array('FieldError');

   public function beforeFilter() {
      $this->Auth->deny('licence','members','download');
   }

   public function beforeRender(){
      AppController::beforeRender();
      $subMenu = array(
		      array ("Membres","/ManageMembers/members",  $this->params['action'] == 'members' ||
													      $this->params['action'] == 'addMember'||
													      $this->params['action'] == 'uploadMembers'||
 														  $this->params['action'] == 'confirmUploadMembers'||
													      $this->params['action'] == 'viewMember'),
		      
		      array ("Licences","/ManageMembers/licence",$this->params['action'] == 'licence'),
			  array ("Fiche club","/ManageMembers/fiche",$this->params['action'] == 'fiche')
      );
      $this->set('subMenu',$subMenu);

      if($this->params['action'] == 'download'){
         $this->layout = 'empty';
      } else {
         $this->layout = 'connected';
      }
       


   }


   public function licence() {
      $this->set('members',$this->loadMembers());
      $licencesAValider = $this->Licence->getLicenceRequested($this->Session->read('Auth.User.club'));
     
      $this->set('licencesAValider', $licencesAValider);
       
      $licencesValider = $this->Licence->getLicenceValidated($this->Session->read('Auth.User.club'));
      $this->set('licencesValider', $licencesValider);
       
      $licencesProduced = $this->Licence->getLicenceProduced($this->Session->read('Auth.User.club'));
      $this->set('licencesProduced', $licencesProduced);
      
      $licencesAlreadyAsked=$this->Licence->find('all',array('fields'=>'user_id','conditions'=>array('year'=>2014)));
      $idsLicencesAlreadyAsked = array();
      foreach($licencesAlreadyAsked as $licenceAlreadyAsked){
      	array_push($idsLicencesAlreadyAsked,$licenceAlreadyAsked['Licence']['user_id']);
      }
      $this->set('licencesAlreadyAsked',$idsLicencesAlreadyAsked);
      
      
       
   }

   public function members() {
      $this->set('members',$this->loadMembers());
   }


   public function addMember() {
      $this->setAutorisedClubs();
      if ($this->request->is('post')) {
         $this->request->data['User']['username_reset'] = $this->RandomGenerator->generateWord();
         $this->request->data['User']['password_reset'] = $this->RandomGenerator->generateWord();
         $this->User->set($this->request->data);
         if($this->User->validates() != true ){
            $this->Session->setFlash(__('Il y a une erreur dans votre formulaire !'));
            return;
         } else {
            if ($this->User->save()) {
               $this->Session->setFlash(__('Votre enregistrement a réussi !'));
               $this->redirect('/ManageMembers/members');
            } else {
               $this->Session->setFlash(__('Error'));
            }
         }
      }
   }

   /**
    *
    *
    nom;prenom;
    nom1;prenom1;mail1
    nom1;prenom1;mail1

    *
    * Enter description here ...
    */

   public function uploadMembers($isRetry=0) {
      $this->setAutorisedClubs();
      if ($this->request->is('post') && !$isRetry) {
         $membersCsv = $this->request->data['User']['members'];
         $clubSelected = $this->request->data['User']['club'];
         $memberRows = explode("\n",$membersCsv);
         $users = $this->extractUserFromCsv($membersCsv,$clubSelected);

         $isValid = true;

         foreach($users as &$user){
            $this->User->set(array('User'=>$user));
            if( $this->User->validates($this->getListOfFieldToValidate()) != true ){
               $user['error'] = $this->User->invalidFields();
               $isValid = false;
            }
         }

         if (!$isValid){
            $this->Session->setFlash(__('Il y a une erreur dans votre fichier !'));
         }
         $this->set("users",$users);//used to populate the list
         $this->set("isValid",$isValid); // to check if confirm button is enable or not
         $this->set("membersCsv",$membersCsv); // add in a hidden field for callback
         $this->set("clubSelected",$clubSelected); // add in a hidden field for callback
         $this->render("confirm_upload_members");
      } else if($this->request->is('get')){
        
      }
   }

   public function confirmUploadMembers(){
      $membersCsv = $this->request->data['User']['members'];
      $clubSelected = $this->request->data['User']['club'];
      $users = $this->extractUserFromCsv($membersCsv,$clubSelected);

      foreach ($users as &$user){
         $user['username_reset'] = $this->RandomGenerator->generateWord();
         $user['password_reset'] = $this->RandomGenerator->generateWord();
      }

      $this->User->saveAll($users);
      $this->redirect('/ManageMembers/members');
   }

   public function download(){
      $this->layout='empty';
      //create a file
      $filename = "export_".date("Y.m.d").".csv";

      header('Content-type: application/csv');
      header('Content-Disposition: attachment; filename="'.$filename.'"');

      $members = $this->loadMembers();
      $this->set('members',$members);
   }

   public function fiche(){
   }
   
   
   private function extractUserFromCsv($membersCsv,$clubSelected){
      $memberRows = explode("\n",$membersCsv);
      $users = array();
      foreach ($memberRows as $memberRow){
         $fields = explode(";",$memberRow);
         if(count($fields) > 9){
            $mappedfields = $this->mapToUserFields($fields);
            $mappedfields['club'] = $clubSelected;
            array_push($users, $mappedfields);
         }
      }
      return $users;
   }


   private function mapToUserFields($fields){
      $user['nom']= $fields[0];
      $user['prenom']= $fields[1];
      $user['date_naissance']= $fields[2];
      $user['lieu_de_naissance']= $fields[3];
      $user['sexe']=$fields[4];
      $user['adresse']= $fields[5];
      $user['code_postal']= $fields[6];
      $user['ville']= $fields[7];
      $user['mail']= $fields[8];
      $user['fixephone']= $fields[9];
      $user['gsm']=trim($fields[10]); // to evict \n
      return $user;
   }

   private function getListOfFieldToValidate(){
      $fieldList = array('fieldList' => array('nom','prenom','date_naissance','lieu_de_naissance','sexe','adresse','code_postal','ville','mail'));
      return $fieldList;
   }

   private function loadMembers(){

      if($this->isManageAutorisationAllowed()){
         return  $this->User->find('all',array('order'=>'User.nom,User.prenom'));
      } else if($this->isManageMemberAllowed()){
      	 return $this->User->find('all', array('conditions'=> array('User.club' => $this->Session->read('Auth.User.club')),
      	 									   'order'=>'User.nom,User.prenom'                                     
      	                                      )
      	                         );
      }

   }
   public function viewMember($id){
   	  $this->request->data= $this->User->findById($id);
   }
   public function editMember(){
   	  $data=$this->request->data;
   	  $this->User->set($data);
   	  if($this->User->validates() != true ){
            $this->Session->setFlash(__('Il y a une erreur dans votre formulaire !'));
            $this->render('view_member');
            return;
         } else {
            if ($this->User->save()) {
               $this->Session->setFlash(__('Votre enregistrement a réussi !'));
               $this->redirect('/ManageMembers/members');
            } else {
               $this->Session->setFlash(__('Error'));
            }
         }
   }
   
   

}

?>